package com.oscar.ehome.view.messageview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.oscar.ehome.R;
import com.oscar.ehome.base.fragment.BaseFragment;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.bean.messageBean.MessageListBean;
import com.oscar.ehome.bean.messageBean.MessagesBean;
import com.oscar.ehome.presenter.MessageListPreaenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.utils.view.MyList;
import com.oscar.ehome.utils.view.progressview.ProgressFrameLayout;
import com.oscar.ehome.utils.xrefresh.XRefreshView;
import com.oscar.ehome.view.loginview.LoginActivity;
import com.oscar.ehome.view.messageview.adapter.MessageListAdapter;
import com.oscar.ehome.view.messageview.view.MessageListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by on 2017/5/19 16:12.
 * 消息页
 *
 * @author mengwanhe
 */

public class MessageFragment extends BaseFragment<MessageListView, MessageListPreaenter> implements MessageListView, XRefreshView.XRefreshViewListener,
        AdapterView.OnItemClickListener, ProgressFrameLayout.AgainRequestListener {


    Unbinder unbinder;
    @BindView(R.id.message_serach_img)
    ImageView messageSerachImg;
    @BindView(R.id.message_text)
    TextView messageText;
    @BindView(R.id.serach_message)
    RelativeLayout serachMessage;
    @BindView(R.id.title_image_right)
    ImageView titleImageRight;
    @BindView(R.id.message_title_layout)
    RelativeLayout messageTitleLayout;
    @BindView(R.id.message_listview)
    MyList messageListview;
    @BindView(R.id.pop_views)
    View popViews;
    @BindView(R.id.message_refview)
    XRefreshView messageRefview;
    @BindView(R.id.mess_fragment)
    ProgressFrameLayout messFragment;

    private View view;

    int refresh = 1;//刷新
    private int page = 1;//页数
    private int page_size = 20;//每页的条数
    private int network = 0;//是否有网
    private int size = 0;
    private int count = 0;//条数
    private String token = "";
    private List<MessageListBean> lists = new ArrayList<MessageListBean>();//数据源
    //adpater
    MessageListAdapter adapter;
    //网络请求
    MessageListPreaenter messagePreaenter;
    public static long lastRefreshTime;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_message, null);
        unbinder = ButterKnife.bind(this, view);
        messageTitleLayout.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getColor()));
        onClick();
        initView();
        initData();
        return view;
    }

    @Override
    protected MessageListPreaenter createPresenter() {
        messagePreaenter = new MessageListPreaenter(this);
        return messagePreaenter;
    }

    /**
     * 初始化
     */
    public void initView() {
        token = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getToken();
        String userBeans = SystemConfigFactory.getInstance(getActivity()).getSystemConfig().getUserBean();
        UserBean userbean = new Gson().fromJson(userBeans, UserBean.class);
        if (userbean != null) {
            if ("1".equals(userbean.getIsReleaseOaNotify())) {//显示发布消息
                titleImageRight.setVisibility(View.VISIBLE);
            } else {
                titleImageRight.setVisibility(View.GONE);
            }
        }

        adapter = new MessageListAdapter(getActivity(), lists);
        messageListview.setAdapter(adapter);
    }

    /**
     * 加载数据
     */
    public void initData() {
        if (isNetWork()) {
            messFragment.stopRefresh();
            messageListview.setVisibility(View.VISIBLE);
            String s = String.valueOf(page);
            messagePreaenter.messagelist(token, s, "20", "", "", "");
            showLoading();
        } else {
            messFragment.setVisibility(View.VISIBLE);
            messFragment.setLoadFail();
            messageListview.setVisibility(View.GONE);
        }
    }

    public void onClick() {
        messageListview.setOnItemClickListener(this);
        messFragment.setAgainRequestListener(this);


        messageRefview.setXRefreshViewListener(this);
        // 设置是否可以下拉刷新
        messageRefview.setPullRefreshEnable(true);
        // 设置是否可以上拉加载
        messageRefview.setPullLoadEnable(false);
        // 设置上次刷新的时间
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        //当下拉刷新被禁用时，调用这个方法并传入false可以不让头部被下拉
        messageRefview.setMoveHeadWhenDisablePullRefresh(true);
        // 设置时候可以自动刷新
        messageRefview.setAutoRefresh(false);
    }

    @OnClick({R.id.title_image_right, R.id.serach_message, R.id.message_close, R.id.message_close_re})
    public void OnClicks(View view) {
        switch (view.getId()) {//
            case R.id.title_image_right://筛选
//                Intent intent = new Intent(getActivity(), PopWindowSizerActivity.class);
//                startActivity(intent);
//                popView.setVisibility(View.VISIBLE);
//                getActivity().overridePendingTransition(R.anim.menushow, R.anim.menuhide);
                Intent intent = new Intent(getActivity(), IssueMessageActivity.class);
                startActivity(intent);
                break;
            case R.id.serach_message://搜索
                Intent intentSerach = new Intent(getActivity(), SerachMessageActivity.class);
                startActivity(intentSerach);
                break;


        }
    }

    @Override
    public void getMessageList(MessagesBean result) {
        if (refresh == 2) {
            refresh = 1;
        } else {
            refresh = 1;
            dismissLoading();
        }

        network = 0;
        if (result != null) {
            if (page == 1) {
                lists.clear(); // 将原有的内容清空
            }
            lists = result.getList();
            count = result.getCount();
            size = lists.size();
            if (lists.size() > 0) {
                messageRefview.stopRefresh();
                messFragment.stopRefresh();
                messageListview.setVisibility(View.VISIBLE);
                if (size < page_size && lists.size() > 0) {
//                        messageRefview.setLoadComplete(false);
                    messageRefview.stopLoadMore();
                } else {
                    ToastUtil.show(getActivity(), "换个类型试试吧！");
                }
                adapter.setLists(lists);
            } else {
                messageListview.setVisibility(View.GONE);
                messFragment.setNoResult();
            }

        } else {
            messageListview.setVisibility(View.GONE);
            messFragment.setNoResult();
        }
    }

    @Override
    public void deleteMessageList(String result) {

    }

    @Override
    public void erroy() {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(getActivity(), getString(R.string.erry));
        messFragment.setLoadFail();
        messageListview.setVisibility(View.GONE);
    }

    @Override
    public void erry(String result) {
        dismissLoading();
        messageRefview.stopRefresh();
        ToastUtil.show(getActivity(), result);
        if (result.contains("过期")) {
            getActivity().getSharedPreferences("appbase", Context.MODE_PRIVATE).edit().clear().commit();
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().SetLogin(false);
            SystemConfigFactory.getInstance(getActivity()).getSystemConfig().setIsFirst(true);
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
            getActivity().finish();
        } else {
            messFragment.setLoadFail();
            messageListview.setVisibility(View.GONE);
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        popViews.setVisibility(View.GONE);
        if (CommonUtils.pop == 2) {
            CommonUtils.pop = 1;
            initData();
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onDestroy() {
        messagePreaenter.onDestory();
        super.onDestroy();
    }

    /**
     * 判断是否有网
     */
    public boolean isNetWork() {
        boolean netWork = true;
        if (!CommonUtils.isNetConn(getActivity())) {
            netWork = false;
            return netWork;
        }
        return netWork;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String ids = lists.get(position).getId();
        String type = lists.get(position).getType();
        Intent intent = new Intent(getActivity(), MessageDetilActivity.class);
        intent.putExtra("ids", ids);
        intent.putExtra("type", type);
        CommonUtils.pop = 2;
        startActivity(intent);
    }

    @Override
    public void againRequest() {
        if (isNetWork()) {
            initData();
        } else {
            ToastUtil.show(getActivity(), R.string.pull_to_refresh_network_error);
        }
    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onRefresh(boolean isPullDown) {
        lastRefreshTime = messageRefview.getLastRefreshTime();
        messageRefview.restoreLastRefreshTime(lastRefreshTime);
        page = 1;
        refresh = 2;
        String s = String.valueOf(page);
        messagePreaenter.messagelist(token, s, "20", "", "", "");
    }

    @Override
    public void onLoadMore(boolean isSilence) {
        refresh = 2;
        page++;
        String s = String.valueOf(page);
        messagePreaenter.messagelist(token, s, "20", "", "", "");
    }

    @Override
    public void onRelease(float direction) {

    }

    @Override
    public void onHeaderMove(double headerMovePercent, int offsetY) {

    }
}
